using GTM = Gadgeteer.Modules;
using Gadgeteer.Interfaces;
using Gadgeteer;
using System.Threading;

namespace Coding4Fun.BluetoothPanoHead
{
    /// <summary>
    /// A camera remote shutter module for Microsoft .NET Gadgeteer
    /// </summary>
    public class ShutterControl : GTM.Module
    {
        // Keep track of this module's socket object so that we can control the pins
        readonly Socket _socket;

        // We'll need two GPIO pins defined
        readonly DigitalOutput _focus;
        readonly DigitalOutput _shutter;

        /// <summary>ctor</summary>
        /// <param name="socketNumber">The socket that this module is plugged into</param>
        public ShutterControl(int socketNumber)
        {
            // Get the Gadgeteet Socket for the specified socket number
            _socket = Socket.GetSocket(socketNumber, true, this, null);

            // Define two GPIO pins and set their initial state to false
            _focus = new DigitalOutput(_socket, Socket.Pin.Three, false, this);
            _shutter = new DigitalOutput(_socket, Socket.Pin.Four, false, this);
        }

        /// <summary>
        /// Toggle the pin set to enable/disable the camera focus line
        /// </summary>
        /// <param name="value">Set the state of the line</param>
        private void SetFocus(bool value)
        {
            _focus.Write(value);
        }

        /// <summary>
        /// Toggle the pin set to enable/disable the camera shutter line
        /// </summary>
        /// <param name="value">Set the state of the line</param>
        private void SetShutter(bool value)
        {
            _shutter.Write(value);
        }

        /// <summary>
        /// Take a picture.  Simulate the remote control by closing the focus circuit, then the shutter circuit.
        /// </summary>
        /// <param name="shutterTime">The period of time to hold the circuits closed in ms</param>
        public void TakePicture(int shutterTime)
        {
            // Tell the camera to focus
            SetFocus(true);

            // wait 1/10 of a second
            Thread.Sleep(100);

            // Tell the camera to open the shutter
            SetShutter(true);

            // Hold the shutter open for the specified time
            if (shutterTime > 0)
            {
                Thread.Sleep(shutterTime);
            }

            // Let go of the shutter
            SetShutter(false);

            // let go of the focus
            SetFocus(false);
        }

        /// <summary>
        /// Take a picture with the shutter held down for 1/4 second.
        /// </summary>
        public void TakePicture()
        {
            TakePicture(250);
        }
    }
}
